package com.test.redis.config;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.test.redis.entity.DataSourceMessage;
import com.test.redis.service.DynamicDataSourceManager;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.connection.MessageListener;
import org.springframework.stereotype.Component;

/**
 * Redis消息监听器
 * 监听数据源变更消息并处理
 * @author Administrator
 */
@Slf4j
@Component
public class DataSourceMessageListener implements MessageListener {
    
    @Autowired
    private DynamicDataSourceManager dataSourceManager;
    @Autowired
    ObjectMapper objectMapper;
    
    @Override
    public void onMessage(Message message, byte[] pattern) {
        try {
            Object messageBody = new String(message.getBody());
            if (messageBody instanceof String) {
                // 这里需要将消息反序列化为DataSourceMessage对象
                // 实际实现中可以使用JSON反序列化
                // 为了简化示例，这里直接调用处理方法
                log.debug("接收到Redis消息: {}", messageBody);
                
                // 实际实现中需要解析消息内容
                 DataSourceMessage dataSourceMessage = objectMapper.readValue((String) messageBody, DataSourceMessage.class);
                 dataSourceManager.handleDataSourceMessage(dataSourceMessage);
            }
        } catch (Exception e) {
            log.error("处理Redis消息失败: {}", e.getMessage(), e);
        }
    }
}